<template>
  <div style="background-color: #ececec; padding: 20px">
    <a-row :gutter="16">
      <a-col :span="6">
        <a-card title="选择你要查看的公司" style="text-align: center;" :bordered="false">
          <a-col :span="24">
            <a-cascader v-model:value="selectedCompany" :options="companyOptions" placeholder="请选择公司"
              @change="handleChange" change-on-select style="width: 100%;margin: 2px" />
          </a-col>
        </a-card>

      </a-col>
      <a-col :span="6">
        <a-card title="企业员额定制数" :bordered="false">
          <p>{{ memberCount }}人</p>
        </a-card>
      </a-col>

      <a-col :span="6">
        <a-card title="企业总人数" :bordered="false">
          <p>{{ departUserCount }}人</p>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card title="企业空编人数" :bordered="false">
          <p>{{ memberDiffCount }}人</p>
        </a-card>
      </a-col>

    </a-row>
    <!-- 中间 -->
    <a-row :gutter="16" style="margin-top: 20px;">
      <a-col :span="12">
        <a-card :title="bumentitle" :bordered="false">
          <div id="bar-chart" style="width: 100%; height: 400px;"></div>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card title="企业学历情况" :bordered="false">
          <div id="rose-chart" style="width: 100%; height: 400px;"></div>
        </a-card>
      </a-col>
    </a-row>
    <!-- 下面 ip 统计 -->
    <a-row style="margin-top: 20px;">
      <a-col :span="24">
        <a-card :loading="loading" :bordered="false" title="最近一周访问量统计">
          <div class="infoArea">
            <HeadInfo title="今日IP" :iconColor="ipColor" :content="loginfo.todayIp" icon="environment"></HeadInfo>
            <HeadInfo title="今日访问" :iconColor="visitColor" :content="loginfo.todayVisitCount" icon="team"></HeadInfo>
            <HeadInfo title="总访问量" :iconColor="seriesColor" :content="loginfo.totalVisitCount" icon="rise"></HeadInfo>
          </div>
          <LineMulti :chartData="lineMultiData" height="33vh" type="line" :option="{ legend: { top: 'bottom' } }">
          </LineMulti>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import * as echarts from "echarts";
import { ref, watch, onMounted } from 'vue';
import { useRootSetting } from '/@/hooks/setting/useRootSetting';
//统计ip
const loading = ref(true);
setTimeout(() => {
  loading.value = false;
}, 500);
const { getThemeColor } = useRootSetting();
import LineMulti from '/@/components/chart/LineMulti.vue';
import HeadInfo from '/@/components/chart/HeadInfo.vue';
import { getLoginfo, getVisitInfo, statistics, getUserData, indexDepTreeSync, getHomerData } from './api';
const loginfo = ref<any>({});
const lineMultiData = ref<any>([]);
const QYXL = ref<any>([]);
//企业总人数排行
const serdata1 = ref<any>([]);
const serdata2 = ref<any>([]);
const serdataX = ref<any>([]);
const bumentitle = ref<any>();
//缩放比例
const bili = ref<any>();
//学历图
const xueli = ref<any>({});
const xuelihart = ref<any>();
const selectedCompany = ref<any>();
//企业总人数
const departUserCount = ref('');
//企业额定员额数量 memberCount
const memberCount = ref('');
//企业空缺编制数memberDiffCount
const memberDiffCount = ref('');
const companyOptions = ref<any>([]);

const ipColor = ref();
const visitColor = ref();
const seriesColor = ref();

/**
 * 获取下拉信息
 */
function getUserDetail() {
  getUserData().then((async res => {
    const datas = { orgCode: res.result.orgCode }
    indexDepTreeSync(datas).then((async res => {
      console.log('用户个人数据', res)
      companyOptions.value = transformData(res);
      // handleChange(res[0].id)
      console.log('用户res[0].id', res[0].id)
      selectedCompany.value = res[0].departName
    }));
  }));
}
const handleChange = (value: string) => {
  console.log(`selected ${value}`);
  const depvalue = value[value.length - 1]
  const depId = {
    depId: depvalue
  }
  getHomerData(depId).then((res) => {

    QYXL.value = res.fullTimeEducationCount
    departUserCount.value = res.departUserCount || 0
    memberDiffCount.value = res.memberDiffCount || 0
    memberCount.value = res.memberCount || 0
    //orgColumnList数组 departName memberCount userCount orgColumnName
    serdataX.value = []
    serdata1.value = []
    serdata2.value = []
    bumentitle.value = res.orgColumnName
    for (let i = 0; i < res.orgColumnList.length; i++) {
      console.log(res.orgColumnList[i])
      serdataX.value.push(res.orgColumnList[i].departName)
      serdata1.value.push(res.orgColumnList[i].memberCount)
      serdata2.value.push(res.orgColumnList[i].userCount)
    }
    // 如果数据长度大于 10 个，启用 dataZoom
    if (res.orgColumnList.length > 10) {
      bili.value = 20
    } else {
      bili.value = 100
    }
    //重新渲染echarts
    duozhu()
    xuelichartV();
  });
};
function transformData(data) {
  return data.map(item => ({
    value: item.id,
    label: item.departName,
    children: item.children ? transformData(item.children) : undefined
  }));
}
// 初始化日志信息
function initLogInfo() {
  getLoginfo(null).then((res) => {
    if (res.success) {
      Object.keys(res.result).forEach((key) => {
        res.result[key] = res.result[key] + '';
      });
      loginfo.value = res.result;
    }
  });
  getVisitInfo(null).then((res) => {
    if (res.success) {
      lineMultiData.value = [];
      res.result.forEach((item) => {
        lineMultiData.value.push({ name: item.type, type: 'ip', value: item.ip, color: ipColor.value });
        lineMultiData.value.push({ name: item.type, type: 'visit', value: item.visit, color: visitColor.value });
      });
    }
  });
}


function xuelichartV() {
  const chartContainer1 = document.getElementById('rose-chart');
  if (chartContainer1) {
    xuelihart.value = echarts.init(chartContainer1);
    xueli.value = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        bottom: '2%',
        left: 'center'
      },
      series: [
        {
          name: '企业学历情况',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          labelLine: {
            show: true
          },
          data: QYXL.value
        }
      ]
    };

    xuelihart.value.setOption(xueli.value);

    // 添加窗口调整大小的监听器
    window.addEventListener('resize', () => {
      xuelihart.value.resize();
    });
  } else {
    console.error("Chart container not found");
  }
}
function duozhu() {
  //柱状图配置
  const chartContainer = document.getElementById('bar-chart');
  if (chartContainer) {
    const myChart = echarts.init(chartContainer);
    xueli.value = {

      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {},
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      yAxis: {
        type: 'value',
        boundaryGap: [0, 0.01]
      },
      // 添加 dataZoom 组件
      dataZoom: [
        {
          type: 'slider', // 显示滑动条
          show: true,
          xAxisIndex: [0], // 针对 x 轴进行缩放
          start: 0,       // 数据窗口范围的起始百分比
          end: bili.value         // 数据窗口范围的结束百分比
        },
        {
          type: 'inside',  // 鼠标滚轮缩放
          xAxisIndex: [0], // 针对 x 轴进行缩放
          start: 0,        // 数据窗口范围的起始百分比
          end: bili.value         // 数据窗口范围的结束百分比
        }
      ],
      xAxis: {
        type: 'category',
        data: serdataX,
        axisLabel: {
          interval: 0, // 强制显示所有标签
          rotate: 45, // 旋转45度
          formatter: function (value: string) {
            // 添加换行
            return value.length > 10 ? value.match(/.{1,10}/g)?.join('\n') : value;
          },
          margin: 10 // 增加标签与轴线的间距
        },
      },
      series: [
        {
          name: '定额人数',
          type: 'bar',
          data: serdata1.value
        },
        {
          name: '实际人数',
          type: 'bar',
          data: serdata2.value
        }
      ]
    };

    myChart.setOption(xueli.value);

    // 添加窗口调整大小的监听器
    window.addEventListener('resize', () => {
      myChart.resize();
    });
  } else {
    console.error("Chart container not found");
  }
}
onMounted(() => {
  getUserDetail();
  xuelichartV();
  duozhu();
  // 监测 companyOptions 的变化，默认选择第一个公司
  watch(companyOptions, (newOptions) => {
    if (newOptions.length > 0) {
      // 默认选中第一个公司
      selectedCompany.value = [newOptions[0].value]; // Cascader 需要数组形式
      handleChange(selectedCompany.value);
    }
  });
});
watch(
  () => getThemeColor.value,
  () => {
    seriesColor.value = getThemeColor.value;
    visitColor.value = '#67B962';
    ipColor.value = getThemeColor.value;
    initLogInfo();
  },
  { immediate: true }
);
</script>
<style>
.infoArea {
  display: flex;
  justify-content: space-between;
  padding: 0 10%;

  .head-info.center {
    padding: 0;
  }

  .head-info {
    min-width: 0;
  }
}

/* 首页访问量统计 */
.head-info {
  position: relative;
  text-align: left;
  padding: 0 32px 0 0;
  min-width: 125px;

  &.center {
    text-align: center;
    padding: 0 32px;
  }

  span {
    color: rgba(0, 0, 0, 0.45);
    display: inline-block;
    font-size: 0.95rem;
    line-height: 42px;
    margin-bottom: 4px;
  }

  p {
    line-height: 42px;
    margin: 0;

    a {
      font-weight: 600;
      font-size: 1rem;
    }
  }
}
</style>
